package com.applink.sell_proof;

import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.applink.sell_proof.api.DataHelper;
import com.applink.sell_proof.api.DataResult;
import com.applink.sell_proof.api.Methods;
import com.applink.sell_proof.builder.ProductModelBuilder;

public class SearchProductModel extends Activity implements OnEditorActionListener, Observer {

	private ProductModelBuilder	mBuilder;
	
	public static final int SEARCH_PRODUCT = 100;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle("Search Product Model");
		setContentView(R.layout.search_product_model);
		((EditText) findViewById(R.id.search_box)).setOnEditorActionListener(this);
		mBuilder = new ProductModelBuilder(this, (ViewGroup) findViewById(android.R.id.list));
	}

	@Override
	protected void onResume() {
		super.onResume();
		DataHelper.getInstance().addObserver(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		DataHelper.getInstance().deleteObserver(this);
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent key) {
		if (actionId == EditorInfo.IME_ACTION_SEARCH) {
			DataHelper.getInstance().searchProductModel(v.getText().toString());
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void update(Observable observerable, Object data) {
		if (data == null)
			return;
		DataResult result = (DataResult) data;
		if (result.getMethodName() == Methods.searchProductModel) {

			if (result.getData() == null) {
				TextView tv = (TextView) findViewById(R.id.no_result);
				tv.setVisibility(View.VISIBLE);
				return;
			}

			TextView tv = (TextView) findViewById(R.id.no_result);
			tv.setVisibility(View.INVISIBLE);
			mBuilder.setData((List<? extends Object>) result.getData());
		}
	}
}
